/**
 * 
 */
package idv.takeshi.software.productline.bookstore.application.service.spring;

import idv.takeshi.software.productline.bookstore.domain.model.useraccount.IndividualAccount;
import idv.takeshi.software.productline.bookstore.domain.model.useraccount.UserAccount;
import idv.takeshi.software.productline.bookstore.utils.template.TemplateUtils;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.mail.MessagingException;

import org.springframework.stereotype.Service;

/**
 * A UserRegistrationService implementation specifically for IndividualAccount.
 * @author takeshi
 *
 */
@Service("individualAccountRegistrationService")
public class IndividualAccountRegistrationServiceImpl extends
		AbstractUserRegistrationSerivce {
	
	
	/**
	 * store template path for this service use. 
	 */
	private String templatePath;
	
	/**
	 * @return the templatePath
	 */
	public String getTemplatePath() {
		return templatePath;
	}

	/**
	 * @param templatePath the templatePath to set
	 */
	public void setTemplatePath(String templatePath) {
		this.templatePath = templatePath;
	}
	
	/* (non-Javadoc)
	 * @see idv.takeshi.software.productline.bookstore.application.service.spring.AbstractUserRegistrationSerivce#doSendMail(idv.takeshi.software.productline.bookstore.domain.model.useraccount.UserAccount, java.util.Locale, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected <T extends UserAccount> void doSendMail(T userAccount, Locale locale, String hostUrl) {
		//generate info. for mail
		String mailAddress = userAccount.getEmailAddress();
		String subject = this.getMessageSource().getMessage("mail.activation.subject", null, locale);
		String activationKey = userAccount.getActivationKey();
		String activationKeyUrl = this.getMessageSource().getMessage("mail.activation.key.url", 
				new Object[]{activationKey, userAccount.getAccountName(), hostUrl}, locale);
		String activationKeyLink = this.getMessageSource().getMessage("mail.activation.key.link", 
				new Object[]{activationKeyUrl, activationKey}, locale);
		String mailContent = null;
		
		IndividualAccount individualAccount = (IndividualAccount) userAccount;
		Map variablesHolder = new HashMap();
		variablesHolder.put("userLastName", individualAccount.getLastName());
		variablesHolder.put("activationKeyLink", activationKeyLink);
		
		mailContent = TemplateUtils.generateTemplateString(this.getTemplatePath(), 
				"userAccountActivation.ftl", variablesHolder, locale);
		
		//send mail
		userAccount.setActivationEmailSent(true);
		try{
			this.getMailService().send(mailAddress, subject, mailContent, true);
		}catch(MessagingException e){
			userAccount.setActivationEmailSent(false);
		}
	}

}
